<template>
    <div class="dhzn_shopvip">
        <!-- 店铺会员 -->
        <div class="dhzn_sv-content" v-if="pageingstate !== 1">
            <!-- 查找 -->
            <div class="d_sv-c-query bcwh p10 mb10 br5 bs1g">
                <!-- <button type="button" class="bc4a wh p10 br5 mr10 mb10" @click="pageingstate = 1">添加企业门店</button> -->
                <el-form :model="storequery" ref="storequery" :rules="rules" label-width="50px" class="d_svcq-form" :disabled="this.$route.query.id!==undefined ? true : false">
                    <el-form-item label='筛选' class="mt10 mb10">
                        <el-col :span="3">
                            <el-select v-model="storequery.shopId" @change="requestshopuser()">
                                <el-option label="不限店铺" value=""></el-option>
                                <el-option v-for="(item,key) in shopdata" :key='key' :label="item.name" :value='item.id'></el-option>
                            </el-select>
                        </el-col>
                        <el-col :span="3">
                            <el-select v-model="storequery.state">
                                <el-option label="不限状态" value=""></el-option>
                                <el-option label="已冻结" value="0"></el-option>
                                <el-option label="正常" value="1"></el-option>
                            </el-select>
                        </el-col>
                        <el-col :span="3">
                            <el-select v-model="storequery.select" @change="querystate('storequery');for(var i in storequery) i!=='state' && i!=='shopId' && i!=='select' ? storequery[i] = '' : ''">
                                <el-option label="会员等级" value="1"></el-option>
                                <el-option label="会员归属" value="2"></el-option>
                            </el-select>
                        </el-col>
                        <el-col :span="9">
                            <!-- <el-form-item v-if="storequery.select === '0'" prop="name">
                                <el-input v-model="storequery.name" placeholder="请输入用户名后进行搜索" clearable></el-input>
                            </el-form-item> -->
                            <el-form-item v-if="storequery.select === '1'" prop="level">
                                <!-- <el-cascader class="search-cascader" :options="cityOptions" v-model="storequery.level" @change="changeProvince"></el-cascader> -->
                                <el-select v-model="storequery.level" clearable>
                                    <el-option label="黄金会员" value="0"></el-option>
                                    <el-option label="铂金会员" value="1"></el-option>
                                    <el-option label="钻石会员" value="2"></el-option>
                                </el-select>
                            </el-form-item>
                            <el-form-item v-else prop="userId">
                                <el-select v-model="storequery.userId">
                                    <el-option v-for="(item,key) in shopuser" :key="key" :label="item.name" :value="item.id"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>

                        <el-col :span="6" class="tc">
                            <el-button type="primary" @click="currentPage=1,pageingstate=2;requestshopuser('storequery')">搜索</el-button>
                            <el-button type="danger" @click="currentPage=1,pageingstate=0;requeststore(),querystate('storequery')">取消</el-button>
                        </el-col>
                    </el-form-item>
                </el-form>
            </div>

            <!-- 列表 -->
            <div class="d_sv-c-list bcwh p10 br5 bs1g">

                <div class="d_svcl-title f16 bb1 b p2 mb10"><span v-if="this.$route.query.id!==undefined">{{storequery.shopId | filclassify}}店铺会员</span><span v-else>新增会员：<span @click="pageingstate = 1" class="f24 b00a vm"><i class="el-icon-circle-plus"></i></span></span></div>

                <table class="d_svcl-table tc f14 mb30">
                    <thead>
                        <tr>
                            <th>ID</th>
                            <th>用户ID</th>
                            <th>店铺ID</th>
                            <th>会员等级</th>
                            <!-- <th>所属级别</th> -->
                            <th>积分</th>
                            <th>下级用户数</th>
                            <!-- <th>经纬度</th> -->
                            <th>状态</th>
                            <th>余额</th>
                            <th>累计消费</th>
                            <th>下级总消费</th>
                            <th>入驻时间</th>
                            <th>管理</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr v-for="(item,key) in storelist" :key="key">
                            <td>{{item.id}}</td>
                            <td>{{item.userId | filteruser}}</td>
                            <td>{{item.shopId | filclassify}}</td>
                            <td>{{item.level}}</td>
                            <!-- <td>{{item.userId}}</td> -->
                            <td>{{item.integral}}</td>
                            <td>{{item.userNum}}</td>
                            <td>{{item.state | filterstate}}</td>
                            <!-- <td>{{item.longitude}}-{{item.latitude}}</td> -->
                            <td>{{item.balance}}</td>
                            <td>{{item.consumption}}</td>
                            <td>{{item.subConsumption}}</td>
                            <td>{{item.createTime*1000 | formatDate}} {{item.createTime*1000 | formatDateBehind}}</td>
                            <td>
                                <button type="button" @click="storeupdialog=true;for(var i in storeupdata) i!=='integral' ? storeupdata[i]=String(item[i]) : storeupdata[i]=item[i];storeupdata.key=key" class="bc4a br5 pt5 pb5 wh f14 wsnw"><i class="el-icon-edit"></i>编辑</button>
                                <button type="button" @click="requestfrost(item,key)" class="bcfd wh br5 p5 wh f14 wsnw">冻结<i class="el-icon-close"></i></button>
                            </td>
                        </tr>
                    </tbody>
                </table>
                <!-- 分页 -->
                <div class="d_svcl-block">
                    <el-pagination
                        @size-change="handleSizeChange"
                        @current-change="handleCurrentChange"
                        :current-page="currentPage"
                        :page-size="pagesize"
                        layout="total, prev, pager, next, jumper"
                        :total="total">
                    </el-pagination>
                </div>

                <!-- 弹窗 -->
                <el-dialog title="编辑" :visible.sync="storeupdialog" width="400px">
                    
                    <el-form v-model="storeupdata" ref="storeupdata" label-width="80px" size="mini">
                        <el-form-item label="会员等级">
                            <el-select v-model="storeupdata.level">
                                <el-option label="黄金会员" value="0"></el-option>
                                <el-option label="铂金会员" value="1"></el-option>
                                <el-option label="钻石会员" value="2"></el-option>
                            </el-select>
                        </el-form-item>
                        
                        <el-form-item label="会员积分">
                            <el-col :span="12"><el-input v-model="storeupdata.integral" clearable placeholder="请填写新的店铺名称" cl></el-input></el-col>
                        </el-form-item>

                        <el-form-item label="会员状态">
                            <el-select v-model="storeupdata.state" clearable>
                                <el-option label="冻结" value="0"></el-option>
                                <el-option label="正常" value="1"></el-option>
                            </el-select>
                        </el-form-item>

                    </el-form>

                    <span slot="footer">
                        <el-button @click="storeupdialog=false" size="mini">取 消</el-button>
                        <el-button type="primary" @click="requestupdate(),storeupdialog=false" size="mini">确 定</el-button>
                    </span>
                </el-dialog>
            </div>

        </div>

        <!-- 添加店铺 -->
        <div class="dhzn_s-add bs1g" v-else>
            <div class="bb1 p10 bcwh">
                <span class="vm ff53 f24 b mr10" @click="pageingstate=0"><i class="el-icon-close"></i></span>新增会员：
                <span class="ff53 f14">*经纬度请点击获取后复制，(当前坐标的"，"前的是经度，后面是纬度)</span>
            </div>
            <div class="bcwh p20">
                <el-form :model="storeadd" ref="storeadd" :rules="rules" label-width="80px">
                    <!-- 选择用户 -->
                    <el-form-item label="所属用户">
                        <el-col :span="10">
                            <el-form-item prop="userId">
                                <el-select v-model="storeadd.userId" clearable placeholder="请选择店铺归属">
                                    <el-option v-for="(item,key) in shopuser" :key="key" :label="item.name" :value="item.id"></el-option>
                                </el-select>
                            </el-form-item>
                        </el-col>
                    </el-form-item>

                    <!-- 选择店铺 -->
                    <el-form-item label="所属店铺" prop="shopId">
                        <el-select v-model="storeadd.shopId" clearable placeholder="请选择店铺类型">
                            <el-option v-for="(item,key) in shopdata" :key="key" :label="item.name" :value="item.id"></el-option>
                        </el-select>
                    </el-form-item>

                    <!-- 等级 -->
                    <el-form-item label="会员等级" prop="level">
                        <el-select v-model="storeadd.level" clearable>
                            <el-option label="黄金会员" value="0"></el-option>
                            <el-option label="铂金会员" value="1"></el-option>
                            <el-option label="钻石会员" value="2"></el-option>
                        </el-select>
                    </el-form-item>

                    <el-form-item>
                        <el-button type="primary" @click="requestadd('storeadd')">添加</el-button>
                    </el-form-item>
                </el-form>
            </div>
        </div>

    </div>
</template>

<script>
// 省市区的级联选择器数据
import cityOptions from '../js/city_data2017_element.js'
import {formatDate} from '../js/time.js'
let axios = require('axios')
let that
export default {
    components: {},
    data() {
        return {
            token: '',
            pageingstate: 0,
            storelist: [],
            //全部的店铺
            shopuser: '',
            shopdata: '',
            // 查询的绑定对象
            storequery: {
                shopId: 1,
                select: '1',
                state: '',
                level: '',
                userId: ''
            },
            // 店铺归属的等级
            selectrole:[
                {id:0,type:'合伙人'},
                {id:1,type:"企业"},
                {id:2,type:"普通门店老板"},
                {id:3,type:'企业经销商'},
                {id:4,type:"企业门店老板"},
                {id:5,type:"普通门店店员"},                
                {id:6,type:"企业门店店员"},
                {id:7,type:'普通用户'}
            ],
            // 验证
            rules:{
                level:[
                    {required:true,message:'请设置新增的会员等级',trigger:'change'}
                ],
                userId: [
                    {required:true,message:'请选择会员所属的用户',trigger:'blur'}
                ],
                shopId: [
                    {required:true,message:'请选择会员所属的店铺',trigger:'blur'}
                ]
            },
            // 添加绑定对象
            storeadd: {
               userId: '',
               shopId: '',
               level: '',
               state: 1
            },
            // 修改编辑
            storeupdata: {
                id: '',
                level: '',
                integral: '',
                state: '',
                key:''
            },
            selectname: '',
            currentPage: 1,						//分页的默认页数
            pagesize: 10,                       //单页条数
            total: 0,						   //总条数
            storeupdialog: false,              //弹出层的状态
            cityOptions: cityOptions           //全国的省市区的级联选择器的数据引入绑定
        };
    },
    computed: {},
    watch: {},
    methods: {
        // 用户
        requestuser(){
            let that = this;
            let data = {current:1,size:100000000}
            let updata = JSON.stringify(data)
            // console.log(updata)
            axios({
                method: 'post',
                url: '/api/user/list',
                headers: {
                    'Content-Type': 'application/json',
                    'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`
                },
                data: updata
            }).then( resp=> {
                console.log('用户',resp)
                that.shopuser = resp.data.data;
            }).catch( err=> {console.log(err)})
            // console.log(that.shopuser)
        },

        // 拿到全部店铺
        requeststore(){
            let that = this;
            let data = {current:1,size:100000000}
            let updata = JSON.stringify(data)
            // console.log(updata)
            axios({
                method: 'post',
                url: '/api/shop/list',
                headers: {
                    'Content-Type': 'application/json',
                    'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`
                },
                data: updata
            }).then( resp=> {
                console.log('店铺',resp)
                that.shopdata = resp.data.data;
                if(resp.data.message === '请求成功'){
                    setTimeout(()=>{
                        that.requestshopuser()
                    },200)
                }else{return}
            }).catch( err=> {console.log(err)})
        },

        // 根据店铺选择获取相应的会员
        requestshopuser(){
            let data = {current: that.currentPage,size: that.pagesize};
            for(var i in that.storequery) that.storequery[i] !== '' ? data[i] = that.storequery[i] : '';
            let updata = JSON.stringify(data)
            console.log(updata)
            axios({
                method: 'post',
                url: '/api/shopUser/list',
                headers: {
                    'Content-Type': 'application/json',
                    'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`
                },
                data: updata
            }).then( resp=> {
                console.log('数据',resp)
                if(resp.data.message === '请求成功'){
                    that.storelist = resp.data.data;
                    that.total = resp.data.code;
                    that.pageingstate === 2 ? (
                        resp.data.code !== 0 ? (
                            this.$message({
                                message: '为您找到'+resp.data.code+'位会员',
                                type: 'success'
                            })
                        ) : (this.$message('没有符合条件的会员'))
                    ) : '';
                }else{this.$message.error('失败！请尝试重新登录或刷新页面')}
                
            }).catch( err=> {console.log(err)})
        },

        // 单页条数
        handleSizeChange(val){
            that.pagesize = val;
            that.requestshopuser()
            // if(that.pageingstate === 0){
            //     that.requeststore()
            // }else{that.requestquery('storequery')}
        },

        // 页数
        handleCurrentChange(val){
            that.currentPage = val;
            that.requestshopuser()
            // if(that.pageingstate === 0){
            //     that.requeststore()
            // }else{that.requestquery('storequery')}
        },

        // 查询的状态清除
        querystate(clear){
            this.$refs[clear].resetFields();
        },

        // 添加会员
        requestadd(verify){
            this.$refs[verify].validate((valid)=>{
                if(valid){
                    let data = {totalSales:0,balance:0,score:0,state:1,};
                    for(var i in that.storeadd) data[i] = that.storeadd[i];
                    let updata = JSON.stringify(data);
                    // console.log(data,updata)
                    axios({
                        method: 'post',
                        url: '/api/shopUser/add',
                        headers:{ 
                            'Content-Type': 'application/json',
                            'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`
                        },
                        data: updata
                    }).then( resp=> {
                        console.log(resp)
                        if(resp.data.message==="请求成功"){
                            data.id = resp.data.data;
                            data.integral = 0;
                            data.userNum = 0;
                            data.consumption = 0;
                            data.subConsumption = 0;
                            that.storelist.push(data)
                            that.total += 1;
                            that.pageingstate = 0;
                        }else{}
                    }).catch( err=> {console.log(err)})
                }else{return}
            })
            
        },

        // 修改
        requestupdate(){
            let data = {};
            for(var t in that.storeupdata) that.storeupdata[t] !== '' && t !== 'key' ? data[t] = that.storeupdata[t] : '';
            let updata = JSON.stringify(data);
            console.log(updata,data)
            axios({
                method: 'post',
                url: '/api/shopUser/update',
                headers:{ 
                    'Content-Type': 'application/json',
                    'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`
                },
                data: updata
            }).then( resp=> {
                console.log(resp)
                if(resp.data.message === '请求成功'){
                    let key = that.storeupdata.key;
                    console.log(key)
                    for(var i in data) i==='state' ? that.storelist[key][i] = String(data[i]) : that.storelist[key][i] = data[i];
                }else{}
            }).catch(err=> {console.log(err)})
        },

        // 一键冻结
        requestfrost(item,key){
            // let data = {id:item.id,state:0}
            if(item.state === 0){
                this.$message.error('店铺已冻结请不要重复提交！')
            }else{
                let updata = JSON.stringify({id:item.id,state:0})
                axios({
                    method: 'post',
                    url: '/api/shopUser/update',
                    headers: {
                        'Content-Type': 'application/json',
                        'authorization': `Bearer ${JSON.parse(sessionStorage.getItem('token'))}`
                    },
                    data: updata
                }).then( resp=>{ 
                    console.log(resp)
                    if(resp.data.message === '请求成功'){
                        that.storelist[key].state = 0;
                        this.$message({
                            message: '修改成功!',
                            type: 'success'
                        })
                    }else{}
                }).catch( err=> {console.log(err)})
            }
        },

        // 保留位置拿token
        newtoken(){
            let that = this;
            let axios = require('axios')
			let loguser = JSON.parse(sessionStorage.getItem('updata'))
			let data = {username:loguser.username, password:loguser.password};
			let updata = JSON.stringify(data);
			console.log(updata)
			axios({
				method: 'post',
				url: '/api/getAuthority/manager',
				headers: { 'Content-Type': 'application/json' },
				data: updata
			})
			.then( resp=> {
                that.token = resp.data.data;
				sessionStorage.setItem("token", JSON.stringify(resp.data.data))
                that.requeststore()
                that.requestuser()
			}).catch( err=> {})
        }
    },
    created() {
        that.newtoken()
    },
    mounted() {
        let that = this;
        // console.log(that.storequery.shopId)
        // that.token = JSON.parse(sessionStorage.getItem('token'));
        if(this.$route.query.id !== undefined){
            that.storequery.shopId = this.$route.query.id;
        }
    },
    beforeCreate() {
        that = this;
    },
    beforeMount() {},
    beforeUpdate() {},
    updated() {},
    beforeDestroy() {},
    destroyed() {},
    activated() {},
    
    filters: {
        // 状态
        filterstate(state){
            if(state === 0){
                state = '冻结'
            }else{state = '正常'}
            return state
        },

        // 用户ID转换
        filteruser(user){
            that.shopuser.forEach((item)=>{
                item.id === user ? user = item.nickname : '';
            })
            return user
        },

        // 店铺
        filclassify(type){
            if(that.shopdata !== ''){  
                that.shopdata.forEach((item)=>{
                    item.id === type ? type = item.name : '';
                })
            }
            return type
        },
        // 时间戳过滤器
        formatDate(time){
            var date = new Date(time);
            return formatDate(date,'yyyy-MM-dd')
        },
        formatDateBehind(time){
            var date = new Date(time);
            return formatDate(date,'hh:mm:ss')
        },
    },
}
</script>
<style scoped>
.dhzn_shopvip{
    height: calc(100% - 56px);
    box-sizing: border-box;
}
.dhzn_sv-content{
    height: 100%;
}
/* 查询搜索 */
.search-cascader{
    width: 100%;
}
/* .d_svcq-form .el-form-item{
    margin: 10px 0;
} */
/* 表单数据 */
.d_sv-c-list{
    position: relative;
    height: calc(100% - 90px);
    box-sizing: border-box;
}
.d_svcl-table{
    width: 100%;
    color: #666666;
    border-bottom: 1px solid #e0e0e0;
    border-left: 1px solid  #e0e0e0;
    border-collapse: collapse;
}
.d_svcl-table thead tr,.d_svcl-table tbody tr:hover{
    background-color: #F2F2F2;
}
.d_svcl-table th, .d_svcl-table td{
    min-height: 50px;
    padding: 10px;
    border-top: 1px solid #e0e0e0;
    border-right: 1px solid #e0e0e0;
}
.d_svcl-table tr td img{
    max-width: 120px;
    max-height: 80px;
}
/* 店铺的介绍布局 */
.d_svclt-bodytr{
    min-width: 120px;
    text-align: left;
}
.d_svclt-bodytr p{
    max-width: 240px;
    overflow:hidden; 
    text-indent: 2em;
    text-overflow:ellipsis;
    display:-webkit-box;
    /* autoprefixer: off */
    -webkit-box-orient:vertical;
    /* autoprefixer: on */
    -webkit-line-clamp:3; 
}
/* 分页位置 */
.d_svcl-block{
    position:absolute;
    top: calc(100% - 40px);
}

/* 弹窗 */
.dialog-img{
    display: inline-block;
    width: 100px;
    height: 80px;
    overflow: hidden;
    margin: 3px;
    border-radius: 5px;
    border: 1px dotted #757575;
}
.dialog-img img{
    border-radius: 5px;
    /* max-width: 100%; */
    width: 100%;
    height: 100%;
}
</style>